//
//  Wt.m
//  Bus
//
//  Created by wangjiajia on 13-12-17.
//  Copyright (c) 2013年 wangjiajia. All rights reserved.
//

#import "Wt.h"
#import "MBProgressHUD.h"
#import "Tools.h"
#import "ASIHTTPRequest.h"
#import "UIButton+Bootstrap.h"
#import "UserForm.h"
#import "People.h"
#import "DepNode.h"
#import "WebServicesUtils.h"
#import "JsonParser.h"
#import "DXAlertView.h"
#import "ProcessResult.h"

extern int userId;
extern NSString* userName;

@interface Wt (){
    MBProgressHUD * hud;
    BOOL isPop;
    NSArray* spjsComponent0_Unit;//单位 NSString数组
    NSMutableArray* spjsComponent1_Deps;//部门 DepNode数组
    NSMutableArray* spjsComponent2_People;//人员 People数组
    //选择的人
    People* selectedPeople;
}

@end

@implementation Wt

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    isPop=NO;
    spjsComponent0_Unit=@[@"总公司机关",@"营运单位",@"二级单位"];
    spjsComponent2_People=[NSMutableArray arrayWithCapacity:10];
    [self.chooseSure infoStyle];
    [self.chooseSure setHidden:YES];
    [self.chooseSure addTarget:self action:@selector(choosePeople:) forControlEvents:UIControlEventTouchUpInside];
    //返回按钮
    UIButton *leftButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 60, 30)];
    
    [leftButton setBackgroundImage:[UIImage imageNamed:@"brown_titlebar_back.png"] forState:UIControlStateNormal];
    [leftButton setBackgroundImage:[UIImage imageNamed:@"brown_titlebar_back_selected.png"] forState:UIControlStateHighlighted];
    
    [leftButton setTitle:@" 返回" forState:UIControlStateNormal];
    leftButton.titleLabel.font=[UIFont fontWithName:@"-" size:18];
    [leftButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [leftButton setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
    [leftButton addTarget:self action:@selector(backTo) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *back = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    
    self.navigationItem.leftBarButtonItem = back;
    
    //标题
    self.navigationItem.title=@"审批委托";
    //提交按钮
    [self.submit infoStyle];
    [self.submit addTarget:self action:@selector(submit:) forControlEvents:UIControlEventTouchUpInside];
    //弹出窗体
    [self.wtrTextField addTarget:self action:@selector(showPickView) forControlEvents:UIControlEventTouchDown];//UIControlEventTouchUpInside事件不可以，因为禁用了编辑，根本点击不进去
    //显示字体
    UIFont* font=[UIFont fontWithName:@"-" size:20];
    self.info1.font=font;
    self.info2.font=font;
    self.currentStepName.font=font;
    self.wtrTextField.font=font;
    //当前步奏
    self.currentStepName.text=self.userForm.UpNodeName;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark- 显示与隐藏
-(void)popPickView{
    isPop=YES;//加入了isPop的判断，jbrButton即使不临时禁用，逻辑也OK
    //刷新数据
    //[self.choosePeople reloadComponent:0];
    [self.choosePeople reloadAllComponents];
    //NSLog(@"pop");
    CGContextRef context = UIGraphicsGetCurrentContext();
    [UIView beginAnimations:@"show" context:context];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    [UIView setAnimationDuration:0.6];//动画时间长度，单位秒，浮点数
    [self.view bringSubviewToFront:self.choosePeople];
    [self.view bringSubviewToFront:self.chooseSure];
    CGRect frame=self.choosePeople.frame;
    frame.origin.y+=frame.size.height;
    self.choosePeople.frame =frame;
    
    CGRect sureFrame=self.chooseSure.frame;
    sureFrame.origin.y+=frame.size.height;
    self.chooseSure.frame=sureFrame;
    
    self.chooseSure.hidden=NO;
    [UIView setAnimationDelegate:self];
    
    [UIView commitAnimations];
    
}

-(void)hidePickView{
    //NSLog(@"hide");
    isPop=NO;
    CGContextRef context = UIGraphicsGetCurrentContext();
    [UIView beginAnimations:@"hide" context:context];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    [UIView setAnimationDuration:0.6];//动画时间长度，单位
    CGRect frame=self.choosePeople.frame;
    frame.origin.y-=frame.size.height;
    self.choosePeople.frame =frame;
    
    CGRect sureFrame=self.chooseSure.frame;
    sureFrame.origin.y-=frame.size.height;
    self.chooseSure.frame=sureFrame;
    self.chooseSure.hidden=YES;
    [UIView setAnimationDelegate:self];
    [UIView commitAnimations];
}
#pragma mark- UIPickerViewDataSource

// 返回显示的列数
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return 3;
    
}

// 返回每一列中，显示的行数
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    int count=0;
    
    switch (component) {
        case 0:
            count=spjsComponent0_Unit.count;
            break;
        case 1:
        {
            NSInteger selectedRow=[self.choosePeople selectedRowInComponent:0];
            if(spjsComponent1_Deps&&spjsComponent1_Deps.count>0)
            {
                NSMutableArray* deps=((NSMutableArray*)[spjsComponent1_Deps objectAtIndex:selectedRow]);
                if(deps&&deps.count>0)
                {
                    count=deps.count;
                }
            }
        }
            break;
        case 2:
            count=spjsComponent2_People.count;
            break;
    }
    
    return count;
}

#pragma mark- UIPickerViewDelegate
-(CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component{
    //实测发现，这里宽度设置优先级高于 reusingView
    switch (component) {
        case 0:
            return 100;
        case 1:
            return 120;
        case 2:
            return 80;
        default:
            return 100;
    }
    //或者
    //return 100;
}

-(UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view{
    //使用自定义的视图来替换默认的 实现尺寸大小、字体的设置，优先级高于pickerView:titleForRow:forComponent:
    UILabel* infoLabel=  view?(UILabel*)view:[[UILabel alloc]initWithFrame:CGRectMake(0, 0, 150, 30)];
    infoLabel.font=[UIFont fontWithName:@"-" size:14];
    infoLabel.textAlignment=NSTextAlignmentCenter;
    infoLabel.backgroundColor=UIColorFromRGBA(0x88888844);
    NSString* name;
    
    switch (component) {
        case 0:
        {
            name= [spjsComponent0_Unit objectAtIndex:row];//row=0,1,2 遍历
            //infoLabel.frame=CGRectMake(0, 0, 100, 30);
        }
            break;
        case 1:
        {
            NSInteger selectedRow=[self.choosePeople selectedRowInComponent:0];
            //这里有越界风险,加个判断
            if(((NSMutableArray*)[spjsComponent1_Deps objectAtIndex:selectedRow]).count>row){
                name= ((DepNode*)[((NSMutableArray*)[spjsComponent1_Deps objectAtIndex:selectedRow]) objectAtIndex:row]).depName;}
            //NSLog(@"%@-%@",[spjsComponent0_Unit objectAtIndex:selectedRow],name);
            //infoLabel.frame=CGRectMake(0, 0, 120, 30);
        }
            break;
        case 2:
        {
            if(spjsComponent2_People&&spjsComponent2_People.count>row)
                name= ((People*)[spjsComponent2_People objectAtIndex:row]).userName;
            //infoLabel.frame=CGRectMake(0, 0, 80, 30);
        }
            break;
    }
    
    
    
    
    infoLabel.text=name;
    return infoLabel;
    
}
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
    //初始化时候，会自动选择第一个,但不会触发该事件!只有手动选择才会触发。
    //NSLog(@"didSelectRow");
    NSString* name;
    switch (component) {
        case 0:
            //refresh 1 then refresh 2
        {
            [self.choosePeople reloadComponent:1];
            [self getPeoplesDateAndRefreshComponent2];
        }
            break;
        case 1:
            // just refresh 2
            [self getPeoplesDateAndRefreshComponent2];
            break;
        case 2:
            if(spjsComponent2_People.count>row)
                name=((People*)[spjsComponent2_People objectAtIndex:row]).userName;
            
    }
    
   // if(name)
      //  NSLog(@"选择了%@",name);
}
#pragma mark- 先获取数据，再refresh 2
-(void)getPeoplesDateAndRefreshComponent2{
    NSInteger unit_index=[self.choosePeople selectedRowInComponent:0];
    NSInteger dep_index=[self.choosePeople selectedRowInComponent:1];
    
    if(spjsComponent1_Deps&&spjsComponent1_Deps.count>0){
      NSMutableArray* deps=  (NSMutableArray*)[spjsComponent1_Deps objectAtIndex:unit_index];
        if(deps&&deps.count>0){
          DepNode* depNode=(DepNode*)[deps objectAtIndex:dep_index];
            [WebServicesUtils getExec:[NSString stringWithFormat:@"getDepPeoples @depid=%d",depNode.depId] andTag:108 withDelegete:self];
        }
    }
}


#pragma mark- 自定义函数
-(void)backTo{
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)loading{
    if(!hud)
    {
        hud=[[MBProgressHUD alloc] initWithView:self.view];
        //hud.labelFont=[UIFont fontWithName:@"-" size:16];//放在默认里面
    }
    [Tools showHUD:@"正在获取数据..." andView:self.view andHUD:hud];
    
}

-(void)choosePeople:(id)sender{
    [self hidePickView];
    //还原
    self.wtrTextField.text=@"";
    selectedPeople=nil;
    //选择的行
    int row= [self.choosePeople selectedRowInComponent:2];
    if(spjsComponent2_People&&spjsComponent2_People.count>0)
        selectedPeople= (People*) [spjsComponent2_People objectAtIndex:row];
    //人员多选
    //self.spjsTextField.text=[NSString stringWithFormat:@"%@%@,",self.spjsTextField.text,name];
    //人员单选
    if(selectedPeople)
        self.wtrTextField.text=[NSString stringWithFormat:@"%@,",selectedPeople.userName];
    else
        [Tools toastNotification:@"没有选择委托人!" andView:self.view andLoading:NO andIsBottom:NO];
}
-(void)submit:(id)sender{
    if(!selectedPeople){
        [Tools toastNotification:@"请选择委托人!" andView:self.view andLoading:NO andIsBottom:NO];
    }else{
        
        DXAlertView *alert = [[DXAlertView alloc] initWithTitle:@"审批委托" contentText:[NSString stringWithFormat:@"确定将该表单委托给<%@>处理?",selectedPeople.userName] leftButtonTitle:@"确定" rightButtonTitle:@"取消"];
        
        alert.leftBlock = ^() {
            [WebServicesUtils processWt:self.userForm.Id andUserId:[NSString stringWithFormat:@"%d",userId] andUserName:userName andWtUserId:[NSString stringWithFormat:@"%d",selectedPeople.userId] andWtUserName:selectedPeople.userName withDelegete:self];//self.userForm.Id 不要写成self.userForm.FormId
            
        };
        alert.rightBlock = ^() {
            
        };
        alert.dismissBlock = ^() {
            
        };
        [alert show];
    }
}

-(void)showPickView{
    if(spjsComponent1_Deps){
        if(!isPop)
            [self popPickView];
        else
            [self hidePickView];
    }else{
        //spjsComponent1_Deps数据初始化，结束后再执行后续逻辑。
        //为了确保顺序，可以使用NSMutableArray，发送有序请求，顺序添加。 或者Dictionary，发送无序请求，但指定有序的key。这里使用有序请求。
        spjsComponent1_Deps=[NSMutableArray arrayWithCapacity:3];//初始化，避免nil异常
        [WebServicesUtils getExec:@"select DepID,DepName from Bas_DepInfo where ParentNodesID=1" andTag:105 withDelegete:self];
        
    }
    
    
}

#pragma mark- 禁用键盘
-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    return NO;
}

#pragma mark- 网络
-(void)requestFinished:(ASIHTTPRequest *)request{
    if(request.tag==105){//总公司机关部门
        NSString * responseStr=[request responseString];
        [spjsComponent1_Deps addObject:[JsonParser parseAsDepNode:responseStr]];
        [WebServicesUtils getExec:@"select DepID,DepName from Bas_DepInfo where ParentNodesID=2" andTag:106 withDelegete:self];
    }else if(request.tag==106){//营运单位部门
        NSString * responseStr=[request responseString];
        [spjsComponent1_Deps addObject:[JsonParser parseAsDepNode:responseStr]];
        [WebServicesUtils getExec:@"select DepID,DepName from Bas_DepInfo where ParentNodesID=3" andTag:107 withDelegete:self];
    }else if(request.tag==107){//二级单位部门
        NSString * responseStr=[request responseString];
        [spjsComponent1_Deps addObject:[JsonParser parseAsDepNode:responseStr]];
        //NSLog(@"%@",spjsComponent1_Deps);
        //手动触发click
        [self.wtrTextField sendActionsForControlEvents:UIControlEventTouchDown];
        
    }else if(request.tag==108){//获取到部门人员数据
        NSString * responseStr=[request responseString];
        //为了持有绑定内存的句柄，形参只能add，remove。不能重定向?好吧，我想错了。
        //        [spjsComponent2_People removeAllObjects];
        //        [spjsComponent2_People addObjectsFromArray:[JsonParser parseAsPeoples:responseStr]];
        //可以重定向的，数据源只绑定第一次的内存地址，猜测错误。
        spjsComponent2_People=[JsonParser parseAsPeoples:responseStr];
        [self.choosePeople reloadComponent:2];
    }else if(request.tag==1){//委托
        
        NSString* responseStr=[request responseString];
        //NSLog(@"responseStr=%@",responseStr);
        ProcessResult* pr= [JsonParser parseAsProcessResult:responseStr];
        UIWindow *shareWindow = [UIApplication sharedApplication].keyWindow;
        [Tools toastNotification:pr.msg andView:shareWindow andLoading:NO andIsBottom:NO andHideTime:5];
        if(pr.result==1){
            //返回待办列表
            [self.navigationController popToRootViewControllerAnimated:YES];
        }
    }
}
-(void)requestFailed:(ASIHTTPRequest *)request{
    if(hud){
        [hud hide:YES];
    }
    [Tools toastNotification:@"处理请求失败，请检查网络连接!" andView:self.view andLoading:NO andIsBottom:NO];
}
@end
